using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Collections;
using MBLocale;

/// <summary>
/// Summary description for Localization
/// </summary>
public class Localization
{
	public Localization()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
    //private string getDefaultDateFormat()
    //{
    //    string ret = ""; CultureInfo ci;        
    //    ci = new CultureInfo("");
    //    ret = ci.DateTimeFormat.ShortDatePattern;
    //    ci = null;
    //    return ret;
    //}
    //private string getDefaultDateTimeFormat()
    //{
    //    string ret = ""; CultureInfo ci;
    //    ci = new CultureInfo("");
    //    ret = ci.DateTimeFormat.ShortDatePattern + " " + ci.DateTimeFormat.ShortTimePattern;
    //    ci = null;
    //    return ret;
    //}
    //public string getDateFormat()
    //{
    //    if (HttpContext.Current.Session["userlocale"] == null)
    //        return getDefaultDateFormat();
    //    string ret = "";
    //    CultureInfo ci= new CultureInfo(HttpContext.Current.Session["userlocale"].ToString());
    //    ret = ci.DateTimeFormat.ShortDatePattern;
    //    ci = null;
    //    return ret;
    //}
    //public string getDateTimeFormat()
    //{
    //    if (HttpContext.Current.Session["userlocale"] == null)
    //        return getDefaultDateTimeFormat();
    //    string ret = "";
    //    CultureInfo ci = new CultureInfo(HttpContext.Current.Session["userlocale"].ToString());
    //    ret = ci.DateTimeFormat.ShortDatePattern + " " + ci.DateTimeFormat.ShortTimePattern;
    //    ci = null;
    //    return ret;
    //}
    //public CultureInfo getUserCulture()
    //{
    //    if (HttpContext.Current.Session["userlocale"] == null)
    //        return new CultureInfo("");
    //    CultureInfo ci = new CultureInfo(HttpContext.Current.Session["userlocale"].ToString());
    //    return ci;
    //}
    //public string getInvariantDate(string input)
    //{
    //    if (input.Trim().Length < 1) return input;
    //    try
    //    {
    //        DateTime dt = DateTime.Parse(input, getUserCulture());
    //        return dt.ToString(CultureInfo.InvariantCulture);
    //    }
    //    catch (Exception e)
    //    {
    //        return "";
    //    }
    //}
    //public string getInvariantDateTime(string input)
    //{
    //    if (input.Trim().Length < 1) return input;
    //    try
    //    {
    //        DateTime dt = DateTime.Parse(input, getUserCulture());
    //        return dt.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
    //    }
    //    catch (Exception e)
    //    {
    //        return "";
    //    }
    //}

    //public string getUserCurrency(double value)
    //{
    //    try
    //    {
    //        //return value.ToString("N2", getUserCulture()); // Commanded by 'Imran Gani' on 09-Aug-12.
    //        return string.Format(getUserCulture(), "{0:#,#.00}", value); // Modified by 'Imran Gani' on 28-Aug-12, for currency format.
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("getUserCurrency : Error : " + ex.Message);
    //        return value.ToString("#0.00");
    //    }
    //}
    //public string getUserCurrencyCode() // Implemented by 'Imran Gani' on 09-Aug-12, for currency Code.
    //{
    //    try
    //    {
    //        CultureInfo ci = getUserCulture();
    //        RegionInfo country = new RegionInfo(new CultureInfo(ci.Name).LCID);
    //        return country.ISOCurrencySymbol.ToString();
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("getUserCurrencyCode : Error : " + ex.Message);
    //        return "";
    //    }
    //}
    #endregion

    /// <summary>
    /// converts the datetime for storing and retrieving
    /// </summary>
    /// <param name="input">input date time value</param>
    /// <param name="timeZoneOffest">user's time zone offeset</param>
    /// <param name="isForStoring">for saving the data</param>
    /// <param name="isSystem">true for displaying modefied_at OR created_at</param>
    /// <returns>converted datetime value</returns>
    public string getDateTime4TimeZone(string input, string timeZoneOffest, bool isForStoring, bool isSystem)
    {
        #region Old Code commented by 'Imran Gani' on 28-Feb-2014, for method overridding.
        //string sValue = "";
        //string sDateTimeFormatString = getDateFormat() + " hh:mm tt";
        //DateTime dt = new DateTime();
        //try
        //{
        //    string sHours = "";
        //    string sMinutes = "";
        //    if (input == "") return input;
        //    if (timeZoneOffest != "")
        //    {
        //        if (isForStoring)
        //        {
        //            if (timeZoneOffest.StartsWith("-"))
        //                timeZoneOffest = "+" + timeZoneOffest.Substring(1);
        //            else if (timeZoneOffest.StartsWith("+"))
        //                timeZoneOffest = "-" + timeZoneOffest.Substring(1);
        //            else if (timeZoneOffest.Trim() != "0")
        //                timeZoneOffest = "+" + timeZoneOffest;
        //        }
        //        if (timeZoneOffest.IndexOf('.') != -1)
        //        {
        //            sHours = timeZoneOffest.Substring(1, timeZoneOffest.IndexOf('.') - 1);
        //            sMinutes = timeZoneOffest.Substring(timeZoneOffest.IndexOf('.') + 1, timeZoneOffest.Length - timeZoneOffest.IndexOf('.') - 1);
        //        }
        //        else
        //            sHours = timeZoneOffest.Substring(1, timeZoneOffest.Length - 1);

        //        if (timeZoneOffest.StartsWith("-"))
        //        {
        //            sHours = "-" + sHours;
        //            if (sMinutes != "")
        //                sMinutes = "-" + sMinutes;
        //        }
        //    }
        //    if (sHours == "") sHours = "0";
        //    if (isForStoring)
        //        dt = DateTime.Parse(input, getUserCulture());
        //    else
        //        dt = DateTime.Parse(input, CultureInfo.InvariantCulture); //DateTime.Parse(input);//sanal on Sept 04, 2008
        //    dt = dt.AddHours(Convert.ToDouble(sHours));
        //    if (sMinutes != "")
        //        dt = dt.AddMinutes(Convert.ToDouble(sMinutes));
        //    if (isForStoring)
        //        sValue = dt.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
        //    else
        //        sValue = isSystem==true ? dt.ToString(sDateTimeFormatString) : dt.ToLocalTime().ToString(sDateTimeFormatString); //dt.ToString(sDateTimeFormatString);//sanal on Sept 04, 2008
        //        //sValue = isSystem == true ? dt.ToString(sDateTimeFormatString) : dt.ToUniversalTime().ToString(sDateTimeFormatString); // modified by srivatsan
        //}

        //catch (Exception ex)
        //{
        //    LogWriter.WriteLog("getInvariantDateTime : Error : " + ex.Message);
        //    sValue = input;
        //}
        //return sValue;
        #endregion
        return getDateTime4TimeZone(input, timeZoneOffest, isForStoring, isSystem, false);
    }

    public string getDateTime4TimeZone(string input, string timeZoneOffest, bool isForStoring, bool isSystem,bool isDate)
    {
        string sValue = "";
        //string sDateTimeFormatString = getDateFormat() + " hh:mm tt"; // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        string sDateTimeFormatString = MBLocalization.getDateFormat(HttpContext.Current.Session["userlocale"].ToString()) + " hh:mm tt"; // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
        DateTime dt = new DateTime();
        try
        {
            string sHours = "";
            string sMinutes = "";
            if (input == "") return input;
            if (timeZoneOffest != "")
            {
                if (isForStoring)
                {
                    if (timeZoneOffest.StartsWith("-"))
                        timeZoneOffest = "+" + timeZoneOffest.Substring(1);
                    else if (timeZoneOffest.StartsWith("+"))
                        timeZoneOffest = "-" + timeZoneOffest.Substring(1);
                    else if (timeZoneOffest.Trim() != "0")
                        timeZoneOffest = "+" + timeZoneOffest;
                }
                if (timeZoneOffest.IndexOf('.') != -1)
                {
                    sHours = timeZoneOffest.Substring(1, timeZoneOffest.IndexOf('.') - 1);
                    sMinutes = timeZoneOffest.Substring(timeZoneOffest.IndexOf('.') + 1, timeZoneOffest.Length - timeZoneOffest.IndexOf('.') - 1);
                }
                else
                    sHours = timeZoneOffest.Substring(1, timeZoneOffest.Length - 1);

                if (timeZoneOffest.StartsWith("-"))
                {
                    sHours = "-" + sHours;
                    if (sMinutes != "")
                        sMinutes = "-" + sMinutes;
                }
            }
            if (sHours == "") sHours = "0";
            if (isForStoring)
                dt = DateTime.Parse(input, MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString()));  // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
            //dt = DateTime.Parse(input, getUserCulture()); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
            else
                dt = DateTime.Parse(input, CultureInfo.InvariantCulture); //DateTime.Parse(input);//sanal on Sept 04, 2008

            if (!isDate)
            {
                dt = dt.AddHours(Convert.ToDouble(sHours));
                if (sMinutes != "")
                    dt = dt.AddMinutes(Convert.ToDouble(sMinutes));
            }
            if (isForStoring)
                sValue = dt.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
            else
            {
                if (!isDate)
                    sValue = isSystem == true ? dt.ToString(sDateTimeFormatString) : dt.ToLocalTime().ToString(sDateTimeFormatString); //dt.ToString(sDateTimeFormatString);//sanal on Sept 04, 2008
                else
                    sValue = dt.ToString();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getInvariantDateTime : Error : " + ex.Message);
            sValue = input;
        }
        return sValue;
    }

    /// <summary>
    /// To format the data input to locale base data.
    /// </summary>
    /// <param name="sInput">Data to be formatted.</param>
    /// <param name="sDatatype">DataType of a data.</param>
    /// <param name="sColName">Column name of a data.</param>
    /// <param name="sUTC_Offset">UTC offset values for datatime fields.</param>
    /// <param name="DDI">DynamicDisplayI Object.</param>
    /// <param name="currencyCode_Rate">Currency details for currency fields.</param>
    /// <returns></returns>
    public string getLocaleFormattedValue(string sInput, string sDatatype, string sColName, string sUTC_Offset, DynamicDisplayI DDI, ArrayList currencyCode_Rate)
    {
        try
        {
            if (sInput != "" && sInput != "&nbsp;")
            {
                switch (sDatatype.ToLower())
                {
                    case "dt":
                        if (sColName.ToLower().Trim() == "modified at" || sColName.ToLower().Trim() == "created at")
                            sInput = getDateTime4TimeZone(sInput, sUTC_Offset, false, true);
                        else
                            sInput = getDateTime4TimeZone(sInput, sUTC_Offset, false, false);
                        break;
                    case "da":
                        sInput = MBLocalization.getLocalizedDate(HttpContext.Current.Session["userlocale"].ToString(), DateTime.Parse(sInput));
                        break;
                    case "cu":
                        sInput = DDI.manageCurrency(sInput, currencyCode_Rate);
                        break;
                    case "nu":
                    case "an":
                        sInput = MBLocalization.getLocalizedInteger(HttpContext.Current.Session["userlocale"].ToString(), int.Parse(sInput));
                        break;
                    case "dc":
                    case "fl":
                        sInput = MBLocalization.getLocalizedDecimal(HttpContext.Current.Session["userlocale"].ToString(), double.Parse(sInput));
                        break;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("MBFunctions : getLocaleFormattedValue : Error : " + e.Message);
        }
        return sInput;
    }

    /// <summary>
    /// To format the entire column of datatable which has data for locale format.
    /// </summary>
    /// <param name="dtObj">Datatable to be format.</param>
    /// <param name="sDataType">DataType of a column.</param>
    /// <param name="sColName">Column Name of formating data.</param>
    /// <returns>Locale Formatted datatable.</returns>
    public DataTable getLocalizedColumns(DataTable dtObj, string sDataType, string sColName)
    {
        try
        {
            switch (sDataType.ToLower())
            {
                case "dt":
                    DynamicDisplayI DDI = new DynamicDisplayI();
                    DataColumn dc = null;
                    string strTempCol = sColName + "_Temp";
                    Localization loc = new Localization();
                    string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
                    dc = new DataColumn(strTempCol, typeof(string));
                    dtObj.Columns.Add(dc);
                    dc.SetOrdinal(dtObj.Columns[sColName].Ordinal);
                    foreach (DataRow dr in dtObj.Rows)
                    {
                        if (dr[sColName].ToString() != "")
                            dr[strTempCol] = loc.getDateTime4TimeZone(dr[sColName].ToString(), sUTC_Offset, false, false);
                    }
                    dtObj.Columns.Remove(sColName);
                    dtObj.Columns[strTempCol].ColumnName = sColName;
                    break;
                case "da":
                    string[] sDateCols = { sColName };
                    dtObj = MBLocalization.getLocalizedDate(HttpContext.Current.Session["userlocale"].ToString(), dtObj, sDateCols);
                    break;
                case "nu":
                case "an":
                    string[] sIntegerCols = { sColName };
                    dtObj = MBLocalization.getLocalizedInteger(HttpContext.Current.Session["userlocale"].ToString(), dtObj, sIntegerCols);
                    break;
                case "cu":
                case "dc":
                case "fl":
                    string[] sDecimalCols = { sColName };
                    dtObj = MBLocalization.getLocalizedDecimal(HttpContext.Current.Session["userlocale"].ToString(), dtObj, sDecimalCols);
                    break;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("MBFunctions : getLocalizedColumns : Error : " + e.Message);
        }
        return dtObj;
    }

    public string getDBValueFromLocale(string sInput, string DataType)
    {
        try
        {
            if (sInput != "")
            {
                switch (DataType.ToLower())
                {
                    case "dt":
                        DynamicDisplayI DDI = new DynamicDisplayI();
                        sInput = getDateTime4TimeZone(sInput, DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id"), true, false);
                        DDI = null;
                        break;
                    case "da":
                        sInput = MBLocalization.getDateValue(HttpContext.Current.Session["userlocale"].ToString(), sInput);
                        break;
                    case "cu":
                    case "dc":
                    case "nu":
                    case "an":
                        sInput = MBLocalization.getNumericValue(HttpContext.Current.Session["userlocale"].ToString(), sInput).ToString();
                        break;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("MBFunctions : getDBValueFromLocale : Error : " + e.Message);
        }
        return sInput;
    }
}
